import React, { useState, useEffect } from "react";
import { Form, Card, Button, Input, message } from "antd";
import { createAip, getById, modifyOne } from "../../../services/products";

function Edit(props) {
  const handleSubmit = (values) => {
    if (props.match.params.id) {
      modifyOne(props.match.params.id, values)
        .then((res) => {
          if (res.code === "success") {
            message.success(res.message);
            props.history.push("/admin/products");
          } else {
            message.error(res.message);
          }
        })
        .catch((error) => {
          console.log(error);
        });
    } else {
      createAip(values)
        .then((res) => {
          if (res.code === "success") {
            message.success(res.message);
            props.history.push("/admin/products");
          } else {
            message.error(res.message);
          }
        })
        .catch((error) => {
          console.log(error);
        });
    }
  };
  const onFinishFailed = (errorInfo) => {
    message.error("请输入正确的内容！");
    console.log("Failed:", errorInfo);
  };

  const priceValidator = (rule, value) => {
    if (value * 1 > 100) {
      return Promise.reject("价格不能大于100!");
    } else {
      // todo:此处调用api接口进行操作
      return Promise.resolve();
    }
  };

  const [currentData, setCurrentData] = useState({});

  useEffect(() => {
    if (props.match.params.id) {
      getById(props.match.params.id).then((res) => {
        console.log(res);
        setCurrentData(res);
      });
    }
  }, []);
  return (
    <Card title="商品编辑">
      <Form onFinish={handleSubmit} onFinishFailed={onFinishFailed}>
        <Form.Item
          label="名称"
          name="name"
          rules={[{ required: true, message: "请输入商品名称" }]}
          initialValue={currentData.name}
        >
          <Input placeholder="请输入商品名称" />
        </Form.Item>
        <Form.Item
          label="价格"
          name="price"
          rules={[
            { required: true, message: "请输入商品价格" },
            { validator: priceValidator },
          ]}
          initialValue={currentData.price}
        >
          <Input placeholder="请输入商品价格" />
        </Form.Item>
        <Button type="primary" htmlType="submit">
          保存
        </Button>
      </Form>
    </Card>
  );
}

export default Edit;
